package gov.kqqzyyy.monkey.tjpd.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import gov.kqqzyyy.monkey.tjpd.R;
import gov.kqqzyyy.monkey.tjpd.mytools.MyBaseActivity;
import gov.kqqzyyy.monkey.tjpd.mytools.MyServiceUtil;
import gov.kqqzyyy.monkey.tjpd.mytools.UpdateInfo;
import gov.kqqzyyy.monkey.tjpd.objects.TJ_ZSLB;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FragmentPreferences extends MyBaseActivity {

    private List<TJ_ZSLB> mResultList;

    private Call<String> zslbCall;

    private PrefsFragement prefsFragement;

    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        doGetZSLB();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (zslbCall != null && zslbCall.isExecuted()) {
            zslbCall.cancel();
        }
        if (prefsFragement != null && prefsFragement.serverTestThread != null && prefsFragement.serverTestThread.isAlive()) {
            prefsFragement.serverTestThread.interrupt();
            prefsFragement.serverTestThread = null;
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
            startActivity(intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public List<TJ_ZSLB> getmResultList() {
        return mResultList;
    }

    // 设置类
    public static class PrefsFragement extends PreferenceFragment implements Preference.OnPreferenceChangeListener {

        SharedPreferences mSharedPreferences;
        ListPreference mClinicAreaPreference; //诊区列表
        EditTextPreference mServerAddPreference; //服务器地址

        List<TJ_ZSLB> mResultList;
        List<String> zsmcList;//诊区名称
        List<String> zsidList;//诊区识别

        String defaultClinic;
        String preServerAdd;

        MyHandler myHandler;
        Thread serverTestThread;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mSharedPreferences = getPreferenceManager().getSharedPreferences();
            myHandler = new MyHandler((FragmentPreferences) getActivity());
            addPreferencesFromResource(R.xml.preferences);//从XML文件加载选项
            onBindXML();
            setAddressText();
            mServerAddPreference.setOnPreferenceChangeListener(this);
            mResultList = ((FragmentPreferences) getActivity()).getmResultList();
            if (mResultList.size() > 0) {
                zsmcList = new ArrayList<>();
                zsidList = new ArrayList<>();
                for (TJ_ZSLB zxlb : mResultList
                        ) {
                    zsmcList.add(zxlb.getZsmc());
                    zsidList.add(String.valueOf(zxlb.getZsid()));
                }
                CharSequence[] zsmcArray = zsmcList.toArray(new CharSequence[0]);
                CharSequence[] zsidArray = zsidList.toArray(new CharSequence[0]);
                mClinicAreaPreference.setEntries(zsmcArray);
                mClinicAreaPreference.setEntryValues(zsidArray);
                mClinicAreaPreference.setOnPreferenceChangeListener(this);
                defaultClinic = mSharedPreferences.getString("clinicarea_name", "");
                if (!defaultClinic.equals("")) {
                    mClinicAreaPreference.setSummary(defaultClinic);
                    int pos = zsmcList.indexOf(defaultClinic);
                    if (pos >= 0) {
                        mClinicAreaPreference.setValueIndex(pos);
                    } else {
                        mClinicAreaPreference.setValueIndex(0);
                    }
                } else {
                    mClinicAreaPreference.setValueIndex(0);
                    mClinicAreaPreference.setSummary(zsmcArray[0]);
                    mSharedPreferences.edit().putString("clinicarea_name", zsmcArray[0].toString()).apply();
                }
            }
        }

        private void setAddressText() {
            preServerAdd = mSharedPreferences.getString("server_address", getString(R.string.default_server));
            mServerAddPreference.setText(preServerAdd);
            mServerAddPreference.setSummary(preServerAdd);
        }

        private void onBindXML() {
            mServerAddPreference = (EditTextPreference) findPreference("server_address");
            mClinicAreaPreference = (ListPreference) findPreference("clinic_preference");
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                CharSequence[] entries = listPreference.getEntries();
                int index = listPreference.findIndexOfValue((String) newValue);
                listPreference.setSummary(entries[index]);
                boolean isChanged = !newValue.toString().equals(defaultClinic);
                if (isChanged) {
                    defaultClinic = newValue.toString();
                    mSharedPreferences.edit().putString("clinicarea_name", (String) entries[index]).apply();
                }
            } else {
                ((FragmentPreferences) getActivity()).showProgressDialog("服务器连接测试中");
                final String newAdd = newValue.toString();
                serverTestThread = new Thread(() -> {
                    Message message = new Message();
                    if (UpdateInfo.isServerAvailable(newAdd)) {
                        message.what = 0x11;
                    } else {
                        message.what = 0x12;
                        mSharedPreferences.edit().putString("server_address", preServerAdd).apply();
                    }
                    myHandler.sendMessage(message);
                    serverTestThread.interrupt();
                    serverTestThread = null;
                });
                serverTestThread.start();
            }
            return true;
        }

    }

    private static class MyHandler extends Handler {
        WeakReference<FragmentPreferences> mActivity;

        MyHandler(FragmentPreferences activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FragmentPreferences activity = mActivity.get();
            activity.cancelProgressDialog();
            switch (msg.what) {
                case 0x11:
                    Toast.makeText(activity, "服务器连接成功,重启该界面", Toast.LENGTH_SHORT).show();
                    activity.doRestart();
                    break;
                case 0x12:
                    Toast.makeText(activity, "服务器连接失败，重置默认地址", Toast.LENGTH_SHORT).show();
                    break;
            }
            activity.prefsFragement.setAddressText();
        }
    }

    private void doRestart() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    private void doGetZSLB() {
        showProgressDialog("获取诊室类别中");
        zslbCall = MyServiceUtil.getZslbCall();
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                String result = response.body();
                if (result != null) {
                    mResultList = gson.fromJson(result, new TypeToken<List<TJ_ZSLB>>() {
                    }.getType());
                    if (mResultList != null && mResultList.size() > 0) {
                        cancelProgressDialog();
                        prefsFragement = new PrefsFragement();
                        getFragmentManager().beginTransaction().replace(android.R.id.content, prefsFragement).commit();
                    } else {
                        timeToGetZQXX();
                    }
                } else {
                    timeToGetZQXX();
                }

            }

            @Override
            public void onFailure(@NonNull Call<String> call, Throwable t) {
                cancelProgressDialog();
                Toast.makeText(getApplicationContext(), "获取诊室失败" + t.toString(), Toast.LENGTH_SHORT).show();
                timeToGetZQXX();
            }
        };
        zslbCall.enqueue(callback);
    }

    private void timeToGetZQXX() {
        countDownTimer = new CountDownTimer(3000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                Toast.makeText(getApplicationContext(), "获取失败，即将重新获取！", Toast.LENGTH_SHORT).show();
                doGetZSLB();
            }
        }.start();
    }

}